var storeInfo={},storeCombo,config = parent.parent.CONFIG; 
var W = window.parent;

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择门店',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:true,module:'kpi'},
			width : 460,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var sp_code = [];
				var sp_name = [];
				for(var i=0;i<selected.length;i++){
					sp_code.push(selected[i].sp_code);
					sp_name.push(selected[i].sp_name);
				}
				$("#shopCode").val(sp_code.join(","));
				$("#shop_name").val(sp_name.join(","));
				THISPAGE.refreshData();
			},
			cancel:true
		});
	}
};

var THISPAGE = {
	init:function(){
		this.initDom();
		this.initDate();
		THISPAGE.refreshData();
	},
	initDom:function(){
		this.needQueryHourPeriodChart = true;
	},
	initDate:function(){
		$("#querydate").val(DateToFullDateTimeString(new Date()));
		$("#srcQueryDate").val(DateToFullDateTimeString(new Date()));
		this.getWeek();
		this.formatDateAndWeek(DateToFullDateTimeString(new Date()));
	},
	getWeek:function(date){
		 var week,weekString,huanBiLastWeekStr; 
		 if(date != undefined && date != null && date.indexOf("-") > -1 ){
			 var arys1 = new Array();
			 arys1=date.split('-');
			 var ssdate = new Date(arys1[0],parseInt(arys1[1]-1),arys1[2]); 
			 week = ssdate.getDay();   
		 }else{
			 week = new Date().getDay();
		 }
		 if(week==0){weekString="星期日";huanBiLastWeekStr="环比上周日";}
		 if(week==1){weekString="星期一";huanBiLastWeekStr="环比上周一";}
		 if(week==2){weekString="星期二";huanBiLastWeekStr="环比上周二";}
		 if(week==3){weekString="星期三";huanBiLastWeekStr="环比上周三";}
		 if(week==4){weekString="星期四";huanBiLastWeekStr="环比上周四";}
		 if(week==5){weekString="星期五";huanBiLastWeekStr="环比上周五";}
		 if(week==6){weekString="星期六";huanBiLastWeekStr="环比上周六";}
		 $("#week").text(weekString);
		 $("#HuanBiLastWeekSpan").text(huanBiLastWeekStr);
	},
	initStore:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"base/shop/sub_list",
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.data != "" && data.data.length > 0){
					var shops = data.data;
					shops.unshift({"sp_code":"","sp_name":"全部店铺"});
					$('#span_shop').combo({
						value : 'sp_code',
						text : 'sp_name',
						width : 142,
						height : 300,
						listHeight : 300,
						listId : '',
						defaultSelected : 0,
						editable : false,
						callback : {
							onChange : function(data) {
								$("#shopCode").val(data.sp_code);
								THISPAGE.refreshData();
							}
						}
					}).getCombo().loadData(shops);
				}
			}
		 });
	},
	 initPlanChart:function(MonthSellMoney,MonthPlanSellMoney,YearSellMoney,YearPlanSellMoney){
		 var width = $("#chartdw").width();
		var monthPercent = parseFloat(MonthSellMoney)/parseFloat(MonthPlanSellMoney);
		$("#monthPercent").html(Math.round(monthPercent*100)+"%");
		var monthHeight = width;
		var finishMonthHeight = 0;
		if(monthPercent <= 1 ){
			finishMonthHeight = monthHeight*monthPercent;
			$("#monthPercent").css("color","#000");
			$("#monthChart").css("background","#ddd");
		}else{
			$("#monthPercent").css("color","#fff");
			$("#monthChart").css("background","#f90");
			finishMonthHeight = monthHeight/Math.min(monthPercent,1.5);
		}
//		finishMonthHeight = finishMonthHeight - 25;
		$("#monthChart").width(monthHeight);
		$("#finishMonthChart").width(finishMonthHeight);

		
		var yearPercent = parseFloat(YearSellMoney)/parseFloat(YearPlanSellMoney);
		$("#yearPercent").html(Math.round(yearPercent*100)+"%");
		var yearHeight = width;
		var finishYearHeight = 0;
		if(yearPercent <= 1){
			finishYearHeight = yearHeight*yearPercent;
			$("#yearPercent").css("color","#000");
			$("#yearChart").css("background","#ddd");
		}else{
			$("#yearChart").css("background","#f90");
			$("#yearPercent").css("color","#fff");
			finishYearHeight = yearHeight/Math.min(yearPercent,1.5);
		}
//		finishYearHeight = finishYearHeight - 25;
		$("#yearChart").width(yearHeight);
		$("#finishYearChart").width(finishYearHeight);
	},
	initEmptyPlanChart:function(percent){
		$("#monthChart").css("background","#ddd");
		$("#yearChart").css("background","#ddd");
		$("#finishMonthChart").width(0);
		$("#finishYearChart").width(0);
		$("#monthPercent").html(percent);
		$("#yearPercent").html(percent);
	},
	changeDate:function(){
		var newDate = $("#querydate").val();
		var oldDate = $("#srcQueryDate").val();
		if(newDate != oldDate){
			THISPAGE.refreshData();
			$("#srcQueryDate").val(newDate)
			this.getWeek(newDate);
			this.formatDateAndWeek(newDate);
		}
	},
	formatDateAndWeek:function(date){
		var ymd = new Array();
		ymd=date.split('-');
		var fullDate = ymd[0]+"年"+ymd[1]+"月"+ymd[2]+"日";
		$("#theDay").html(fullDate);
		var theWeek = this.getYearWeek(date);
		$("#theWeek").html(ymd[0]+"年第"+theWeek+"周");
	},
	getYearWeek:function(date){
		var ymd = new Array();
		ymd=date.split('-');
		var year = parseInt(ymd[0]);  
		var firstDay = new Date(year, 0, 1);  
		var firstWeekDays = 7 - firstDay.getDay();
		var dayOfYear = (((new Date(year, parseInt(ymd[1],10)-1, parseInt(ymd[2],10))) - firstDay) / (24 * 3600 * 1000)) + 1;  
		return Math.ceil((dayOfYear - firstWeekDays) / 7) + 1; 
	},
	refreshData:function(){
		this.loadWeather();
		this.statDayKpi();
		var CurrentMode = $("#CurrentMode").val();
		this.needQueryHourPeriodChart = true;
		if(CurrentMode == "HourPeriod"){
			this.getHourPeriodChart();
		}
	},
	loadWeather:function(){
		var params = '';
		params += 'shopCode='+$("#shopCode").val();
		params += '&date='+$("#querydate").val();
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'home/loadWeather?'+params,
			data:{},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					var weatherData = data.data;
					$("#we_max_tmp").html($.trim(weatherData.we_max_tmp));
					$("#we_min_tmp").html($.trim(weatherData.we_min_tmp));
					$("#we_name").html($.trim(weatherData.we_name));
					if($.trim(weatherData.city_name) != ""){
						$("#city_name").html($.trim(weatherData.city_name));
					}else{
						$("#city_name").html("&nbsp;");
					}
				}
			}
		});
	},
	statDayKpi:function(){
		var params = '';
		params += 'shopCode='+$("#shopCode").val();
		params += '&date='+$("#querydate").val();
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'home/statDayKpi?'+params,
			data:{},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					var kpiData = data.data;
					$("#comeAmount").html(kpiData.comeAmount);//进店量
					$("#receiveAmount").html(kpiData.receiveAmount);//接待人数
					$("#tryAmount").html(kpiData.tryAmount);//试穿人数
					if(kpiData.comeAmount != 0){//接待率、试穿率
						$("#receiveRate").html(PriceLimit.formatMoney(100*kpiData.receiveAmount/kpiData.comeAmount)+"%");
						$("#tryRate").html(PriceLimit.formatMoney(100*kpiData.tryAmount/kpiData.comeAmount)+"%");
					}else{
						$("#receiveRate").html("0%");
						$("#tryRate").html("0%");
					}
					$("#dealCount").html(kpiData.dealCount);//成交单数
					if(kpiData.receiveAmount != 0){//成交率
						$("#dealRate").html(PriceLimit.formatMoney(100*kpiData.dealCount/kpiData.receiveAmount)+"%");
					}else{
						$("#dealRate").html("0%");
					}
					$("#sellAmount").html(kpiData.sellAmount);//销售数量
					$("#sellMoney").html(kpiData.sellMoney);//销售额
					$("#newVipCount").html(kpiData.newVipCount);//新增会员
					$("#sellMoney_vip").html(kpiData.sellMoney_vip);//会员消费
					$("#costMoney").html(kpiData.costMoney);//成本金额
					$("#profits").html(PriceLimit.formatMoney(kpiData.sellMoney-kpiData.costMoney));//利润
					$("#max_sellMoney").html(kpiData.max_sellMoney);//最高客单价
					if(kpiData.HuanBiYesterday != 0){//环比昨日
						$("#HuanBiYesterday").html(PriceLimit.formatMoney(100*kpiData.sellMoney/kpiData.HuanBiYesterday)+"%");
					}else{
						$("#HuanBiYesterday").html("0%");
					}
					if(kpiData.HuanBiLastWeek != 0){//环比上周几
						$("#HuanBiLastWeek").html(PriceLimit.formatMoney(100*kpiData.sellMoney/kpiData.HuanBiLastWeek)+"%");
					}else{
						$("#HuanBiLastWeek").html("0%");
					}
					if(kpiData.TongBiLastYear != 0){//同比去年
						$("#TongBiLastYear").html(PriceLimit.formatMoney(100*kpiData.sellMoney/kpiData.TongBiLastYear)+"%");
					}else{
						$("#TongBiLastYear").html("0%");
					}
					if(kpiData.dealCount != 0){//连带率、平均客单价
						$("#jointRate").html(PriceLimit.formatMoney(kpiData.sellAmount/kpiData.dealCount));
						$("#avgSellPrice").html(PriceLimit.formatMoney(kpiData.sellMoney/kpiData.dealCount));
					}else{
						$("#jointRate").html("0");
						$("#avgSellPrice").html("0");
					}
					if(kpiData.sellMoney != 0){
						$("#sellMoney_vipRate").html(PriceLimit.formatMoney(100*kpiData.sellMoney_vip/kpiData.sellMoney)+"%");
						$("#profits_rate").html(PriceLimit.formatMoney(100*(kpiData.sellMoney-kpiData.costMoney)/kpiData.sellMoney)+"%");
					}else{
						$("#sellMoney_vipRate").html("0%");
						$("#profits_rate").html("0%");
					}
					if(kpiData.sellAmount != 0){
						$("#avgPrice").html(PriceLimit.formatMoney(kpiData.sellMoney/kpiData.sellAmount));
					}else{
						$("#avgPrice").html("0%");
					}
					if(kpiData.retailMoney != 0){
						$("#avg_Rate").html(PriceLimit.formatMoney(100*kpiData.sellMoney/kpiData.retailMoney)+"%");
					}else{
						$("#avg_Rate").html("0%");
					}
					if(kpiData.allVipCount != 0){
						$("#backRate").html(PriceLimit.formatMoney(100*kpiData.dealVipCount/kpiData.allVipCount)+"%");
					}else{
						$("#backRate").html("0%");
					}
					$("#sh_cash").html(kpiData.sh_cash);
					$("#sh_cd_money").html(kpiData.sh_cd_money);
					$("#sh_vc_money").html(kpiData.sh_vc_money);
					$("#sh_ec_money").html(kpiData.sh_ec_money);
					$("#sh_bank_money").html(kpiData.sh_bank_money);
					$("#sh_mall_money").html(kpiData.sh_mall_money);
					$("#sh_wx_money").html(kpiData.sh_wx_money);
					$("#sh_ali_money").html(kpiData.sh_ali_money);
					$("#sh_lost_money").html(kpiData.sh_lost_money);
					$("#cardCount").html(kpiData.cardCount);
					$("#voucherCount").html(kpiData.voucherCount);
					$("#ecouponCount").html(kpiData.ecouponCount);
					$("#allocate_amount_out").html(kpiData.allocate_amount_out);
					$("#allocate_amount_in").html(kpiData.allocate_amount_in);
					$("#vipBirthday").html(kpiData.vipBirthday);
					//进度
					$("#day_sellMoney").html(kpiData.sellMoney);
					$("#week_sellMoney").html(kpiData.week_sellMoney);
					$("#day_planMoney").html(kpiData.day_planMoney);
					$("#week_planMoney").html(kpiData.week_planMoney);
					if(parseFloat(data.week_planMoney) <= 0){
						THISPAGE.initEmptyPlanChart("0%");
					}else{
						THISPAGE.initPlanChart(kpiData.sellMoney,kpiData.day_planMoney,kpiData.week_sellMoney,kpiData.week_planMoney);
					}
					//活动
					var theDayActivity = kpiData.sales;
					var lastWeekActivity = kpiData.sales_last;
					$("#todayAct").empty();
					$("#lastWeekDayAct").empty();
					if(theDayActivity != undefined && theDayActivity != null && theDayActivity != "" && theDayActivity.length > 0){
						for(var i=0;i<theDayActivity.length;i++){
							$("#todayAct").append("<tr><td width='40px' align='center'>"+(i+1)+"</td><td>"+theDayActivity[i].ss_name+"</td></tr>");
						}
						if(theDayActivity.length<3){
							for(var i=theDayActivity.length;i<3;i++){
								$("#todayAct").append("<tr><td width='40px' align='center'>"+(i+1)+"</td><td>&nbsp;</td></tr>");
							}
						}
					}else{
						for(var i=0;i<3;i++){
							$("#todayAct").append("<tr><td width='40px' align='center'>"+(i+1)+"</td><td>&nbsp;</td></tr>");
						}
					}
					if(lastWeekActivity != undefined && lastWeekActivity != null && lastWeekActivity != "" && lastWeekActivity.length > 0){
						for(var i=0;i<lastWeekActivity.length;i++){
							$("#lastWeekDayAct").append("<tr><td width='40px' align='center'>"+(i+1)+"</td><td>"+lastWeekActivity[i].ss_name+"</td></tr>");
						}
						if(lastWeekActivity.length<3){
							for(var i=lastWeekActivity.length;i<3;i++){
								$("#lastWeekDayAct").append("<tr><td width='40px' align='center'>"+(i+1)+"</td><td>&nbsp;</td></tr>");
							}
						}
					}else{
						for(var i=0;i<3;i++){
							$("#lastWeekDayAct").append("<tr><td width='40px' align='center'>"+(i+1)+"</td><td>&nbsp;</td></tr>");
						}
					}
					
					
				}
			}
		});
	},
	getHourPeriodChart:function(){
		if(!this.needQueryHourPeriodChart){
			return;
		}
		var params = '';
		params += 'shopCode='+$("#shopCode").val();
		params += '&date='+$("#querydate").val();
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'home/statByHour?'+params,
			data:{},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					THISPAGE.buildPeriodChart(data.data);
					THISPAGE.needQueryHourPeriodChart = false;
				}
			}
		});
	},
	buildPeriodChart:function(data){
		var hours = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];
		var come = [];
		var money = [];
		for (var i = 0; i < data.length; i++) {
			come.push(data[i].da_come);
			money.push(data[i].sh_money);
		}
		var chart = new Highcharts.Chart('container', {
		    title: {
		        text: '',
		        x: -20
		    },
		    xAxis: {
		        categories: hours
		    },
		    yAxis: [
		    {
		        title: {text: '客流量'},
		        min: 0,
		        allowDecimals:false,
		        opposite: true
		    },
		    {
		        title: {text: '营业额'}
		    }
		    ],
		    series: [{
		    	type: 'spline',
		        name: '客流量',
		        data: come,
		        marker:{
		        	lineWidth: 2,
		        	lineColor: 'red',
		        	fillColor: 'red'
		        }
		    }, {
		    	type: 'column',
		        name: '营业额',
		        yAxis: 1,
		        data: money,
		        color: '#F7A35C'
		    }]
		});
	},
	changeMode:function(mode){
		$("#CurrentMode").val(mode);
		if(mode == "HourPeriod"){
			$("#HourPeriodMode").addClass("cur");
			$("#StoreKPIMode").removeClass();
			$("#HourPeriodDiv").show();
			$("#everydayDiv").hide();
			this.getHourPeriodChart();
		}else if(mode == "StoreKPI"){
			$("#StoreKPIMode").addClass("cur");
			$("#HourPeriodMode").removeClass();
			$("#HourPeriodDiv").hide();
			$("#everydayDiv").show();
		}
	}
};
THISPAGE.init();

